import re

import requests

import execjs
import hashlib
import gzip
import websocket
from douyin_message_pb2 import PushFrame, Response, ChatMessage
js_code = execjs.compile(open('02.js', 'r', encoding='utf-8').read())


def on_open(ws):
    print("连接建立")

def on_message(ws, body):
    print(body)
    # frame = PushFrame()
    # frame.ParseFromString(body)
    # origin_bytes = gzip.decompress(frame.payload)
    # # 解析Response消息
    # res = Response()
    # res.ParseFromString(origin_bytes)
    # # 心跳检测
    # if res.need_ack:
    #     s = PushFrame()
    #     s.payload_type = 'ack'
    #     s.payload = res.internal_ext.encode('utf-8')
    #     s.LogID = frame.LogID
    #     ws.send(s.SerializeToString())
    #     print("=========心跳检测，响应成功===========")
    # # 遍历所有消息
    # for msg in res.messages:
    #     # print(f"收到消息类型: {msg.method}")
    #     # 判断是否为聊天消息
    #     if msg.method == 'WebcastChatMessage':
    #         chat_msg = ChatMessage()
    #         chat_msg.ParseFromString(msg.payload)
    #         print(f"聊天内容: {chat_msg.content}")
    #         print(f"用户昵称: {chat_msg.user.nickname}")
    #         print(f"用户ID: {chat_msg.user.id}")
    #         print("-" * 50)



def on_error(ws, error):
    print(f"发生错误: {error}")


def on_close(ws, close_status_code, close_msg):
    print("连接关闭")

def get_index():
    url = 'https://live.douyin.com/149570020649'
    headers = {
        "Referer": "https://live.douyin.com/961099326456?enter_from_merge=web_live&enter_method=web_card&room_id=7530249904837495604&action_type=click&group_id=undefined&request_id=undefined&is_livehead_preview_mini_window_show=&enter_method_temai=web_video_head&mini_window_show_type=&search_tab=undefined&live_position=undefined",
        "Upgrade-Insecure-Requests": "1",
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36",
        "sec-ch-ua": "\"Not)A;Brand\";v=\"8\", \"Chromium\";v=\"138\", \"Google Chrome\";v=\"138\"",
        "sec-ch-ua-mobile": "?0",
        "sec-ch-ua-platform": "\"Windows\""
    }
    cookies = {
        "IsDouyinActive": "false",
        "__ac_nonce": "06723018d00888333ca1b",
        "__ac_signature": "_02B4Z6wo00f016ZierAAAIDAOAbaIcG6xsemQn4AAIEg68",
        "__ac_referer": "https://live.douyin.com/961099326456?enter_from_merge=web_live&enter_method=web_card&room_id=7530249904837495604&action_type=click&group_id=undefined&request_id=undefined&is_livehead_preview_mini_window_show=&enter_method_temai=web_video_head&mini_window_show_type=&search_tab=undefined&live_position=undefined"
    }
    res = requests.get(url, headers=headers, cookies=cookies)
    # print(res.text)
    ro_id = re.findall(r'\\"roomInfo\\":\{\\"room\\":\{\\"id_str\\":\\"(.*?)\\",\\"', res.text)[0]
    # print(ro_id)
    da = f'live_id=1,aid=6383,version_code=180800,webcast_sdk_version=1.0.14-beta.0,room_id={ro_id},sub_room_id=,sub_channel_id=,did_rule=3,user_unique_id=7359170990646314547,device_platform=web,device_type=,ac=,identity=audience'
    aa = hashlib.md5(da.encode('utf-8')).hexdigest()
    cookie = res.cookies.get_dict()
    # print(cookie)
    return ro_id, aa, cookie


if __name__ == "__main__":
    ro_id, aa, cookie = get_index()
    print(cookie)
    print(aa)

    headers = {
        "Upgrade": "websocket",
        "Origin": "https://live.douyin.com",
        "Cache-Control": "no-cache",
        "Accept-Language": "zh-CN,zh;q=0.9",
        "Pragma": "no-cache",
        "Connection": "Upgrade",
        "Sec-WebSocket-Key": "OIWkO85IF4hujtaOOmMaBw==",
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36",
        "Sec-WebSocket-Version": "13",
        "Sec-WebSocket-Extensions": "permessage-deflate; client_max_window_bits"
    }
    sign = js_code.call('getSignature', aa)
    print(sign)
    # print(cookie["ttwid"])
    url = f'wss://webcast5-ws-web-hl.douyin.com/webcast/im/push/v2/?app_name=douyin_web&version_code=180800&webcast_sdk_version=1.0.14-beta.0&update_version_code=1.0.14-beta.0&compress=gzip&device_platform=web&cookie_enabled=true&screen_width=1707&screen_height=960&browser_language=zh-CN&browser_platform=Win32&browser_name=Mozilla&browser_version=5.0%20(Windows%20NT%2010.0;%20Win64;%20x64)%20AppleWebKit/537.36%20(KHTML,%20like%20Gecko)%20Chrome/129.0.0.0%20Safari/537.36&browser_online=true&tz_name=Asia/Shanghai&cursor=d-1_u-1_h-7415969050658034722_t-1726664969296_r-1&internal_ext=internal_src:dim|wss_push_room_id:{ro_id}|wss_push_did:7359170990646314547|first_req_ms:1726664969175|fetch_time:1726664969296|seq:1|wss_info:0-1726664969296-0-0|wrds_v:7415969568708889208&host=https://live.douyin.com&aid=6383&live_id=1&did_rule=3&endpoint=live_pc&support_wrds=1&user_unique_id=7359170990646314547&im_path=/webcast/im/fetch/&identity=audience&need_persist_msg_count=15&insert_task_id=&live_reason=&room_id={ro_id}&heartbeatDuration=0&signature={sign}'

    ws_app = websocket.WebSocketApp(
        url,
        header=headers,
        cookie=f'ttwid={cookie["ttwid"]}',
        on_open=on_open,
        on_message=on_message,
        on_error=on_error,
        on_close=on_close
    )

    ws_app.run_forever()
